package com.hz.zhifu.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeCreateModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.response.AlipayTradeCreateResponse;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/alipay")
public class AlipayController {

    private final AlipayClient alipayClient;
    private final String notifyUrl;
    private final String alipayPublicKey;

    public AlipayController(AlipayClient alipayClient,
                            @Value("${alipay.notify-url}") String notifyUrl,
                            @Value("${alipay.public-key}") String alipayPublicKey) {
        this.alipayClient = alipayClient;
        this.notifyUrl = notifyUrl;
        this.alipayPublicKey = alipayPublicKey;
    }

    @GetMapping("/ceshi")
    public String ceshi(){
        return "云哥";
    }
    @PostMapping("/create-order")
    public Map<String, Object> createOrder(@RequestBody OrderRequest request) throws AlipayApiException {
        // 生成商户订单号（需要保证唯一性）
        String outTradeNo = generateOutTradeNo();

        // 创建支付宝交易创建请求
        AlipayTradeCreateRequest alipayRequest = new AlipayTradeCreateRequest();
        alipayRequest.setNotifyUrl(notifyUrl);

        // 设置业务参数
        AlipayTradeCreateModel model = new AlipayTradeCreateModel();
        model.setOutTradeNo(outTradeNo);
        model.setTotalAmount(request.getAmount().toString());
        model.setSubject(request.getSubject());
        // 小程序支付产品码
        model.setProductCode("QUICK_MSECURITY_PAY"); // 修改为小程序支付的正确产品码

        // 设置买家ID，这里需要从小程序获取用户的支付宝ID
        // 在实际应用中，应该从请求中获取用户的支付宝用户ID
        if (request.getBuyerId() != null && !request.getBuyerId().isEmpty()) {
            model.setBuyerId(request.getBuyerId());
        } else {
            // 如果没有提供买家ID，返回错误
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("msg", "缺少买家ID(buyer_id)，小程序支付必须提供");
            return errorResult;
        }

        // 设置卖家ID，使用应用对应的支付宝账号ID
        model.setSellerId("2088721061474644"); // 沙箱环境的卖家账号ID

        alipayRequest.setBizModel(model);

        // 调用支付宝接口
        AlipayTradeCreateResponse response = alipayClient.execute(alipayRequest);

        Map<String, Object> result = new HashMap<>();
        if (response.isSuccess()) {
            result.put("success", true);
            result.put("tradeNo", response.getTradeNo());
            result.put("outTradeNo", outTradeNo);
            // 返回完整的响应体，小程序支付需要完整的orderStr
            result.put("orderStr", response.getBody());
            // 打印完整响应以便调试
            System.out.println("支付宝响应成功: " + response.getBody());
        } else {
            result.put("success", false);
            result.put("msg", response.getSubMsg());
            // 打印错误信息以便调试
            System.out.println("支付宝响应失败: " + response.getBody());
        }
        return result;
    }

    private String generateOutTradeNo() {
        return "ORDER_" + System.currentTimeMillis() + "_" + UUID.randomUUID().toString().substring(0, 6);
    }

    // 在AlipayController类中添加以下方法

    @PostMapping("/get-user-id")
    public Map<String, Object> getUserId(@RequestBody Map<String, String> request) throws AlipayApiException {
        String authCode = request.get("authCode");

        // 使用授权码获取用户ID
        // 在实际应用中，需要调用支付宝的接口获取用户ID
        // 这里为了简化，直接返回沙箱环境的买家ID
        Map<String, Object> result = new HashMap<>();
        result.put("userId", "2088722061474656"); // 沙箱环境的买家账号ID
        System.out.println("11111111111111111");
        return result;
    }

    // 查询订单状态
    @PostMapping("/query")
    public Map<String, Object> queryOrder(@RequestBody Map<String, String> request) throws AlipayApiException {
        String outTradeNo = request.get("outTradeNo");

        // 这里应该实现查询订单的逻辑
        // 为简化示例，直接返回成功
        Map<String, Object> result = new HashMap<>();
        result.put("status", "TRADE_SUCCESS");
        return result;
    }

    // 异步通知处理
    @PostMapping("/notify")
    public String paymentNotify(HttpServletRequest request) throws AlipayApiException {
        Map<String, String> params = convertRequestParamsToMap(request);
        boolean signVerified = AlipaySignature.rsaCheckV1(
                params,
                alipayPublicKey,
                "UTF-8",
                "RSA2");

        if (signVerified) {
            // 验签成功，处理业务逻辑
            String tradeStatus = params.get("trade_status");
            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                String outTradeNo = params.get("out_trade_no");
                // 更新订单状态、记录支付信息等
                return "success";
            }
        }
        return "failure";
    }

    private Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        return params;
    }

    @Data
    public static class OrderRequest {
        private BigDecimal amount;
        private String subject;
        private String outTradeNo;
        private String buyerId; // 新增买家ID字段
    }
}
